<template>
    <div class="icons_wrapper">
        <swiper :options="swiperOptions" v-if="foodTypes.length">
            <swiper-slide v-for="(page, index) of pages" :key="index">
                <div class="icon" v-for="(item, index) of page" :key="index.id">
                    <router-link :to="{path: '/food', query: {geohash, title: item.title, restaurant_category_id: getCategoryId(item.link)}}">
                      <div class="icon-img">
                          <img class="icon-img-content" :src="imgBaseUrl + item.image_url">
                      </div>
                      <p class="icon-desc ellipsis">{{item.title}}</p>
                    </router-link>
                </div>
            </swiper-slide>
        </swiper>
        <img v-else src="@/assets/images/fl.svg" class="fl_back animation_opactiy">
    </div>
</template>

<script>
export default {
  name: 'HomeIcons',
  props: {
    geohash: String,
    foodTypes: Array
  },
  data () {
    return {
      swiperOptions: {
        autoplay: false
      },
      imgBaseUrl: 'https://fuss10.elemecdn.com' // 图片域名地址
    }
  },
  computed: {
    // pages () {
    //   let resLength = this.foodTypes.length
    //   let resArr = [...this.foodTypes] // 返回一个新的数组
    //   let foodArr = []
    //   for (let i = 0, j = 0; i < resLength; i += 8, j++) {
    //     foodArr[j] = resArr.splice(0, 8)
    //   }
    //   return foodArr
    // }

    // 另一种写法
    pages () {
      const pages = []
      this.foodTypes.forEach((item, index) => {
        const page = Math.floor(index / 10)
        if (!pages[page]) {
          pages[page] = []
        }
        pages[page].push(item)
      })
      return pages
    }
  },
  methods: {
    // 解码url地址，求去restaurant_category_id值
    getCategoryId (url) {
      let urlData = decodeURIComponent(url.split('=')[1].replace('&target_name', ''))
      if (/restaurant_category_id/gi.test(urlData)) {
        return JSON.parse(urlData).restaurant_category_id.id
      } else {
        return ''
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/mixins.styl'
  .icons_wrapper >>> .swiper-container
    height: 0
    padding-bottom: 42%;
  .icons_wrapper
    padding: .15rem 0
    .icon
      position: relative
      overflow: hidden
      float: left
      width: 20%
      height: 0
      padding-bottom: 20%;
      .icon-img
        position: absolute
        top: 0
        left: 0
        right: 0
        bottom: .4rem
        box-sizing: border-box
        padding: .1rem
        .icon-img-content
          display: block
          margin: 0 auto
          height: 100%
      .icon-desc
        position: absolute
        left: 0
        right: 0
        bottom: .1rem
        height: .30rem
        line-height: .30rem
        text-align: center
        color: #333
        ellipsis()
</style>
